import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../models/music_model.dart';
import '../services/audio_service.dart';

class MusicListPage extends StatefulWidget {
  @override
  _MusicListPageState createState() => _MusicListPageState();
}

class _MusicListPageState extends State<MusicListPage> {
  final List<Music> _musicList = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _checkPermissionsAndLoadMusic(); // 加载本地音乐文件
  }

  Future<void> _checkPermissionsAndLoadMusic() async {
    // 请求存储权限
    if (await Permission.storage.request().isGranted) {
      await _loadMusicFiles();
    } else {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('需要存储权限才能访问本地音乐')));
    }
  }

  Future<void> _loadMusicFiles() async {
    // 实际应用中应实现本地音乐扫描逻辑

    try {
      // 获取音乐目录
      final directory = Platform.isAndroid
          ? Directory("assets/")
          : Directory('D:\\Download');
      // : await getApplicationDocumentsDirectory();

      if (directory != null) {
        print('加载音乐文件...');
        // 扫描MP3文件
        final musicFiles = directory
            .listSync(recursive: true)
            .where((file) => file.path.endsWith('.mp3'))
            .toList();

        // 构建音乐列表（简化版，实际需解析元数据）
        setState(() {
          _musicList.addAll(
            musicFiles.asMap().entries.map((entry) {
              final index = entry.key;
              final file = entry.value as File;
              final fileName = file.path.split(Platform.pathSeparator).last;
              return Music(
                id: index,
                title: fileName.replaceAll('.mp3', ''),
                artist: '未知艺术家',
                path: file.path,
                url: '',
                duration: '3:45',
                // 实际需获取真实时长
                coverUrl: 'https://picsum.photos/200',
              );
            }),
          );
          context.read<AudioService>().setPlaylist(_musicList);
          _isLoading = false;
        });
      }
      setState(() {
        if (_musicList.isEmpty) {
          print('未找到音乐文件');
          List<Music> musicDemo = [
            Music(
              id: 1,
              title: '示例音乐1',
              artist: '未知艺术家',
              path: '',
              url:
                  'https://lv-sycdn.kuwo.cn/fae0a4fd1575ae0238dc1ff9146dce15/686f6276/resource/30106/trackmedia/M500001M6r7C3BZ1V3.mp3',
              duration: '3:45',
              coverUrl: 'https://picsum.photos/200',
            ),
            Music(
              id: 2,
              title: '示例音乐2',
              artist: '未知艺术家',
              path: '',
              url:
                  'https://er-sycdn.kuwo.cn/ce99c02aa990b7a441345275d26a095e/686f4dc6/resource/30106/trackmedia/M500004ew9im2GqNfJ.mp3',
              duration: '4:12',
              coverUrl: 'https://picsum.photos/201',
            ),
            Music(
              id: 3,
              title: '示例音乐2',
              artist: '未知艺术家',
              path: '',
              url:
                  'https://er-sycdn.kuwo.cn/a4ef896a82985e22657b28dbc8ec165c/686f541a/resource/30106/trackmedia/M500000lXwEL21jeJi.mp3',
              duration: '4:12',
              coverUrl: 'https://picsum.photos/201',
            ),
            Music(
              id: 4,
              title: '示例音乐2',
              artist: '未知艺术家',
              path: '',
              url:
                  'http://antiserver.kuwo.cn/anti.s?rid=MUSIC_1032753&response=res&format=mp3|aac&type=convert_url&br=128kmp3&agent=iPhone&callback=getlink&jpcallback=getlink.mp3',
              duration: '4:12',
              coverUrl: 'https://picsum.photos/201',
            ),
          ];
          _musicList.addAll(musicDemo);
          context.read<AudioService>().setPlaylist(_musicList);
        }
      });
    } catch (e) {
      setState(() => _isLoading = false);
      print('加载音乐失败: \$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      print('正在加载音乐...');
      return Center(child: CircularProgressIndicator());
    }

    // if (_musicList.isEmpty) {
    //   return Center(child: Text('未找到音乐文件'));
    // }
    final audioService = Provider.of<AudioService>(context, listen: true);

    return Scaffold(
      appBar: AppBar(title: const Text('音乐列表')),
      body: Column(
        children: [
          Expanded(
            child: ReorderableListView.builder(
              itemCount: _musicList.length,
              itemBuilder: (context, index) {
                final music = _musicList[index];
                final isPlaying = context.read<AudioService>().currentMusic?.id == music.id && context.read<AudioService>().currentState.playing;
                ListTile musicTile = ListTile(
                  key: Key(music.id.toString()),
                  leading: Image.network(
                    music.coverUrl,
                    errorBuilder: (context, error, stackTrace) =>
                        Image.asset('assets/default_cover.png'), // 使用默认图片
                  ),
                  title: Text(music.title),
                  subtitle: Text('${music.artist} · ${music.duration}'),
                  trailing: isPlaying ? const Icon(Icons.volume_up) : null,
                  onTap: () => context.read<AudioService>().playIndex(index),
                );

                return musicTile;
              },
              onReorder: (oldIndex, newIndex) {
                setState(() {
                  if (oldIndex < newIndex) newIndex--;
                  final item = _musicList.removeAt(oldIndex);
                  _musicList.insert(newIndex, item);
                  context.read<AudioService>().setPlaylist(_musicList);
                });
              },
            ),
          ),
          // 播放控制栏
          // if (audioService.currentMusic != null) _buildControlBar(),
        ],
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
  }
}
